package cn.skycity.common.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.skycity.common.feign.AuthClient;
import cn.skycity.common.service.*;
import cn.skycity.framework.core.model.Result;
import cn.skycity.framework.core.utils.UserUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.skycity.common.log.event.LoginInfoEvent;
import com.skycity.framework.uaa.pojo.dto.LoginDTO;
import com.skycity.framework.uaa.pojo.entity.SysRole;
import com.skycity.framework.uaa.pojo.vo.RouteVO;
import com.skycity.framework.uaa.pojo.vo.SysUserVo;
import com.skycity.framework.uaa.pojo.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 自定义登录
     *
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO, @RequestHeader("Authorization") String authorization) {
        Object token = authClient.getToken(loginDTO.getUsername(), loginDTO.getPassword(), loginDTO.getGrantType(), authorization);
        SpringUtil.getApplicationContext().publishEvent(new LoginInfoEvent());
        return Result.success(token);
    }

    @PostMapping("/logout")
    public Result<?> logout() {
        authClient.logout();
        return Result.success();
    }

    @GetMapping("/test")
    public Result<?> test(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hederName = headerNames.nextElement();

            log.info("{}，{}", hederName, request.getHeader(hederName));
        }
        return Result.success();
    }

    /**
     * 获取用户基本信息、角色信息、按钮权限信息
     * @return
     */
    @GetMapping("/me")
    public Result<UserVO> getCurrentUser() {
        UserVO userVO = new UserVO();
        // 用户基本信息
        SysUserVo user = sysUserService.selectUserById(UserUtils.getUserId());
        BeanUtil.copyProperties(user,userVO,true);
        List<Long> roleList = sysUserRoleService.listRoleIdByUserId(UserUtils.getUserId());
        if(CollUtil.isNotEmpty(roleList)) {
            List<String> roleNames = sysRoleService.list(new LambdaQueryWrapper<SysRole>().in(SysRole::getId, roleList))
                    .stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            userVO.setRoles(roleNames);
            //用户按钮权限信息
            List<String> perms = sysRoleMenuService.listBtnPerms(roleList);
            userVO.setPerms(perms);
        }
        return Result.success(userVO);
    }

    @GetMapping("/routes")
    public Result<List<RouteVO>> getRouteList() {
        return Result.success(menuService.listRoute());
    }
}
